package com.hl.service.impl;

import com.hl.domain.R;
import com.hl.security.LoginUser;
import com.hl.service.LoginService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.RemoteLogService;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;
    @Override
    public R login(String username, String password) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(token);
        if (authenticate == null) {
            return R.error("用户名或密码错误");
        }
        if (authenticate.isAuthenticated()){
            LoginUser user = (LoginUser)authenticate.getPrincipal();
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            // 组装系统用户，最少需要 userId 和 userName（按你业务可以映射会员到系统用户，或用固定 admin 测试）
            SysUser sysUser = new SysUser();
            sysUser.setUserId(1L);
            sysUser.setUserName("admin");
            com.ruoyi.system.api.model.LoginUser ruoyiLoginUser = new com.ruoyi.system.api.model.LoginUser();
            ruoyiLoginUser.setSysUser(sysUser);
            // 可按需塞入权限集合
            ruoyiLoginUser.setPermissions((Set<String>) null);
            ruoyiLoginUser.setRoles((Set<String>) null);
            Map<String, Object> tokenMap = tokenService.createToken(ruoyiLoginUser);
            String accessToken = (String) tokenMap.get("access_token");
            return R.ok(200, accessToken, "登录成功", user.getLiliShopMember());

        }
        return R.error("登录失败");
    }
}
